import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { DatePipe } from '@angular/common';
import { CommonService } from 'src/app/services-common/common.service';
import { ProjectManageService } from '../project-manage.service';

@Component({
  selector: 'app-project-edition',
  templateUrl: './project-edition.component.html',
  styleUrls: ['./project-edition.component.scss'],
  providers: [DatePipe]
})
export class ProjectEditionComponent implements OnInit {

  isCollapse: boolean = true;
  menuLists: Array<any> = [];
  selectedIndex: number = 0;

  searchParams: any = {
    id: '',
    versionName: '', // 版本名称
    versionId: '', // 版本号
    updateFlag: '', // 是否强制更新 0为否 1为是
    note: '', // 备注
    updateDetail: '', // 更新详情
    startTime: '', // 更新开始时间
    endTime: '' // 更新结束时间
  };
  updateDates: any = [];
  searchProName: string = ''; // 项目名称

  tableParams: any = {
    tableLoading: false,
    page: 1,
    pageSize: 20,
    total: 20
  };
  tableData: any = [];

  // 新增 | 编辑
  isModifyVisible: boolean = false;
  modalType: number = 0;
  modalItem: any = {};
  validateForm!: FormGroup;
  fileList: any = [];
  uploadLoading: boolean = false;

  constructor(
    private message: NzMessageService,
    private fb: FormBuilder,
    private datePipe: DatePipe,
    private commonService: CommonService,
    private services: ProjectManageService
  ) { }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      versionName: [''], // 版本名称
      projectName: [''], // 项目名称
      platform: [''], // 平台
      versionId: ['', [Validators.required]], // 版本号
      updateFlag: ['0'], // 是否强制更新 0: 否 1: 是

      packageSize: [''], // 应用包大小
      appUrl: [''], // 应用包下载地址
      note: [''], // 备注
      updateDetail: [''] // 更新详情
    });

    this.loadTable();
  }

  async loadTable() {
    let params  = {
      ...this.searchParams,
      projectName: this.searchProName,
      page: this.tableParams.page,
      pageSize: this.tableParams.pageSize
    }
    this.tableParams.tableLoading = true;
    const res: any = await this.services.queryProjectEditionList(params);
    this.tableParams.tableLoading = false;

    if (res.code == 0) {
      const { list, pageList } = res.data || {};

      this.menuLists = list || [];
      this.tableData = pageList?.records || [];
      this.tableParams.total = pageList?.total || 0;

      this.menuLists.unshift({
        edition: '',
        group: '',
        name: "项目版本",
        platform: ''
      })
    } else {
      this.menuLists = [];
      this.tableData = [];
      this.tableParams.total = 0;
      this.message.error(res.message);
    }
  }

  searchData() {
    this.tableParams.page = 1;
    this.loadTable();
  }
  resetData() {
    for (let key in this.searchParams) {
      this.searchParams[key] = '';
    }
    this.updateDates = [];
    this.tableParams.page = 1;
    this.loadTable();
  }

  dateChange(result: any) {
    this.searchParams.startTime = result.length ? this.datePipe.transform(result[0], 'yyyy-MM-dd') : '';
    this.searchParams.endTime = result.length ? this.datePipe.transform(result[1], 'yyyy-MM-dd') : '';
  }

  updateChange(value: any) {
    if (!value)
      this.searchParams.updateFlag = '';
  }

  menuChange(item: any, index: number) {
    this.selectedIndex = index;
    this.searchProName = item.name;
    if (item.name == '项目版本') {
      this.searchProName = '';
    }
    this.resetData();
  }

  async deleteItem(item: any) {
    const res: any = await this.services.deleteProEditionItem({id: item.id});
    if (res.code == 0) {
      this.message.success('删除成功');
      this.loadTable();
    } else {
      this.message.error(res.message);
    }
  }

  onModalPreview(ev: any) {
    const { originFileObj }: any = ev?.file;
    this.uploadInterface(originFileObj);
  }
  async uploadInterface(file: any) {
    if (!file || this.uploadLoading) {
      return
    }

    try {
      this.uploadLoading = true;
      const res: any = await this.services.uploadPackageData(file, this.proNameChange(this.validateForm.value.projectName));
      this.uploadLoading = false;

      if (res.code == 0) {
        this.message.success('上传成功');
        this.validateForm.get('appUrl')?.setValue(res.data);
        this.validateForm.get('packageSize')?.setValue(file.size);
      } else {
        this.message.error(res.message || '上传失败');
      }
    } catch (error: any) {
      this.uploadLoading = false;
      this.validateForm.get('appUrl')?.setValue('');
      this.validateForm.get('packageSize')?.setValue('');
      this.message.error(error || '上传失败');
    }
  }

  deletePackage() {
    this.validateForm.get('appUrl')?.setValue('');
    this.validateForm.get('packageSize')?.setValue('');
  }

  /**
   * Open Modal
   * @param type 0: Add 1: Edit
   * @param item 
   */
  showEditModal(type: number, item?: any) {
    this.modalType = type;
    this.validateForm.reset();

    if (type === 1) {
      this.modalItem = item;
      this.validateForm.patchValue({
        versionName: item.versionName || '', // 版本名称
        projectName: item.projectName || '', // 项目名称
        platform: item.platform, // 平台
        versionId: item.versionId || '', // 版本号
        updateFlag: String(item.updateFlag), // 是否强制更新 0: 否 1: 是

        packageSize: item.packageSize || '', // 应用包大小
        appUrl: item.appUrl || '', // 应用包下载地址
        note: item.note, // 备注
        updateDetail: item.updateDetail // 更新详情
      })
    } else {
      let proName = this.menuLists.length ? this.menuLists[1]?.name : '';
      this.validateForm.patchValue({
        projectName: proName, // 项目名称
        platform: this.proNameChange(proName),
        updateFlag: '0' // 是否强制更新 0: 否 1: 是
      })
    }

    this.isModifyVisible = true;
  }

  handleCancel() {
    this.isModifyVisible = false;
  }

  async submitForm() {
    if (this.validateForm.valid) {
      let params = {
        projectVersion: {
          ...this.validateForm.value
        }
      }
      for (let key in params.projectVersion) {
        if (params.projectVersion[key] === null) {
          params.projectVersion[key] = '';
        }
      }
      
      let res: any
      if (this.modalType === 0) {
        res = await this.services.saveProEditionItem(params);
      } else {
        params.projectVersion.id = this.modalItem.id;
        res = await this.services.updateProEditionItem(params);
      }

      if (res.code == 0) {
        this.message.success('操作成功');
        this.isModifyVisible = false;
        this.loadTable();
      } else {
        this.message.error(res.message);
      }
    } else {
      Object.values(this.validateForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }

  // 计算包大小
  calculationPackage(sizeNum: number) {
    return sizeNum && !isNaN((sizeNum / 1024 / 1024)) ? (sizeNum / 1024 / 1024).toFixed(2) + 'MB' : '-';
  }

  // Change PageIndex
  onPageIndexChange(index: number) {
    this.tableParams.page = index;
    this.loadTable();
  }
  // Change PageSize
  onPageSizeChange(sizeNum: number) {
    this.tableParams.page = 1;
    this.tableParams.pageSize = sizeNum;
    this.loadTable();
  }

  // 项目名称 Change
  projectChange(value: any) {
    let tmpObj: any = this.menuLists.find((item: any) => item.name === value);
    this.validateForm.get('platform')?.setValue(tmpObj.platform);
  }

  // 平台
  proNameChange(value: any) {
    let tmpObj: any = this.menuLists.find((item: any) => item.name === value);
    return tmpObj?.platform || '';
  }

  interceptStr(url: string) {
    let tmpStr = '';
    if (url) {
      let index = url.lastIndexOf("\/");
      tmpStr = url.substring(index + 1, url.length);
    }
    return tmpStr
  }
}
